from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import ab_aggregation
from datetime import datetime
from .tools.w_statistical_create import create_ab_excel
from django.contrib.auth.decorators import login_required
import json
#异常汇总

@login_required(login_url='/login')
def ab_index(request):
    win, linux, all = sel_ab_data()
    return render(request, 'abnormal/ab-statistical.html', {"sel_win": win, "sel_linux": linux,"table_data":all})

@login_required(login_url='/login')
@csrf_exempt
def statistical_add(request):
    if request.is_ajax():
        if request.method == "POST":
            _status = 1
            try:
                system_json = {'1':"windows",'2':"linux"}
                sa_data = eval(request.POST.get("adddata"))
                mod_date = datetime.now()
                sa_data["system_type"] = system_json[sa_data["system_type"]]
                sa_data["modifyDate"] = mod_date
                sa_data["number"] = 1
                ab_aggregation.objects.create(**sa_data)
                _status=0
            except BaseException as b:
                _log_str = "statistical_add 函数异常：" + str(b)
                print(_log_str)
            finally:
                win, linux, all = sel_ab_data()
                return HttpResponse(json.dumps({"status": _status, "sel_win": win, "sel_linux": linux,"table_data":all}))

@login_required(login_url='/login')
@csrf_exempt
def statistical_ops(request):
    if request.is_ajax():
        if request.method == "POST":
            so_type = int(request.POST.get("type"))
            win = []
            linux = []
            all = []
            _status = 1
            _type = -1
            try:
                if so_type == 0:
                    so_data = int(request.POST.get("data"))
                    ab_aggregation.objects.filter(id=so_data).update(is_delete=1, modifyDate=datetime.now())
                    win, linux, all = sel_ab_data()
                    _status = 0
                    _type = 0
                elif so_type == 1:
                    so_data = eval(request.POST.get("data"))
                    so_id = int(request.POST.get("id"))
                    ab_aggregation.objects.filter(id=so_id).update(**so_data)
                    win, linux, all = sel_ab_data()
                    _status = 0
                    _type = 1
                elif so_type == 2:
                    so_id = int(request.POST.get("id"))
                    num = int(ab_aggregation.objects.filter(id=so_id).values_list('number')[0][0])
                    num +=1
                    ab_aggregation.objects.filter(id=so_id).update(number=num)
                    win, linux, all = sel_ab_data()
                    _status = 0
                    _type = 2
            except BaseException as b:
                _log_err = "statistical_ops函数异常 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({"status": _status, "type":_type, "sel_win": win, "sel_linux": linux,"table_data":all}))

@login_required(login_url='/login')
@csrf_exempt
def statistical_excel(request):
    if request.is_ajax():
        if request.method == "POST":
            se_type = int(request.POST.get("type"))
            se_create = create_ab_excel()
            title = "异常汇总"
            _status = 1
            try:
                if se_type == 0:
                    se_data = eval(request.POST.get("data"))
                    print(se_data)
                    se_create.generate_ab_excel(title, se_data)
                    _status = 0
                elif se_type == 1:
                    win, linux, all = sel_ab_data()
                    se_create.generate_ab_excel(title, all)
                    _status = 0
            except BaseException as b:
               _log_err = "statistical_excel函数异常 --》" + str(b)
               print(_log_err)
            finally:
                return HttpResponse({"status":_status})

#数据操作
def sel_ab_data():
    sad_win_list = []
    sad_linux_list = []
    sad_return_list = []
    try:
        sad_data = ab_aggregation.objects.filter(is_delete=0).values_list('id', 'system_type', 'module_name',
                                                                          'abnormal_paper', 'abnormal_des', 'solution',
                                                                          'ip_addr', 'number', 'createDate')
        sad_name_list = ['id', 'system_type', 'module_name', 'abnormal_paper', 'abnormal_des', 'solution', 'ip_addr',
                         'number', 'createDate']
        sad_win = ab_aggregation.objects.filter(is_delete=0, system_type='windows').values_list(
            'module_name').distinct()
        sad_linux = ab_aggregation.objects.filter(is_delete=0, system_type='linux').values_list(
            'module_name').distinct()
        sad_win_list = [x[0] for x in sad_win]
        sad_linux_list = [x[0] for x in sad_linux]
        sad_return_list = []
        for sad_i in sad_data:
            sad_json = {}
            for sad_x in range(len(sad_name_list)):
                if sad_name_list[sad_x] == "createDate":
                    sad_json[sad_name_list[sad_x]] = sad_i[sad_x].strftime('%Y-%m-%d %H:%M:%S')

                else:
                    sad_json[sad_name_list[sad_x]] = sad_i[sad_x]
            sad_return_list.append(sad_json)
    except BaseException as b:
        _log_err = "sel_ab_data函数异常 --》" + str(b)
        print(_log_err)
    finally:
        return sad_win_list, sad_linux_list, sad_return_list